package com.cksys.achievement.config;

import com.cksys.achievement.exception.NoBindingException;
import com.cksys.achievement.exception.ValidateCodeException;
import com.cksys.achievement.service.impl.CustomUserDetailsServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName: AjaxAuthFailureHandler
 * @author: zyx
 * @E-mail: 1377631190@qq.com
 * @DATE: 2020/4/4 19:44
 */
@Slf4j
@Component
public class AjaxAuthFailureHandler extends SimpleUrlAuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) {
        String result = "{\"payload\":\"${msg}\",\"success\":false,\"msg\":\"${msg}\",\"code\":200}";
        PrintWriter out = null;

        try {
            response.setContentType("application/json;charset=utf-8");
            out = response.getWriter();

            if (exception.getMessage().equals(CustomUserDetailsServiceImpl.USERNAME_NOT_FOUND)){
                result = result.replace("${msg}", "c");
            }

            if (exception.getMessage().equals(CustomUserDetailsServiceImpl.NOT_AUDITED)){
                result = result.replace("${msg}", "用户未审核或未通过！");
            }

            if (exception.getMessage().equals(CustomUserDetailsServiceImpl.NOT_ACTIVATION)) {
                result = result.replace("${msg}", CustomUserDetailsServiceImpl.NOT_ACTIVATION);
            }

            if(exception.getMessage().equals("Bad credentials")){
                result = result.replace("${msg}", "密码错误！");
            }

            if (exception instanceof ValidateCodeException) {
                result = result.replace("${msg}", exception.getMessage());
            }

            if (exception instanceof NoBindingException) {
                response.sendRedirect("/binding");
                return;
            }

        } catch (NoBindingException e) {
            log.info(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            out.write(result);
            out.flush();
            out.close();
        }


    }

}
